#! /usr/bin/env bash

# 编译fdkaac

set -e

# 当前执行脚本所在的文件夹
SCRIPT_DIR=$(cd "$(dirname "$0")";
pwd)

TARGET=$1
SOURCE_REPO=$2
OUTPUT=${BUILD_DIR}/android/fdk-aac-${TARGET}
TOOLCHAIN_PATH=${BUILD_DIR}/android/toolchains/fdk-aac-${TARGET}

cd ${SOURCE_REPO}

# 检测环境属性
. tools/do-detect-env.sh

# 目标平台
TARGET_API=${NDK_MIN_API}
# 交叉编译前缀
CROSS_PREFIX=
TOOLCHAIN_NAME=
# 环境变量
export CC=
export CFLAGS=
export LDFLAGS=
export LIBS=
export CPP=
export CXXCPP=
export CPPFLAGS=
export CXX=
export CXXFLAGS=
export LT_SYS_LIBRARY_PATH=

# 根据生成目标配置参数
case ${TARGET} in

    armv5)
        CROSS_PREFIX=arm-linux-androideabi
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_VER}
    ;;

    armv7a)
        CROSS_PREFIX=arm-linux-androideabi
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_VER}
    ;;

    arm64)
    # android-21或以上平台才支持64位
        TARGET_API=21
        CROSS_PREFIX=aarch64-linux-android
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_64_VER}
    ;;

    x86)
        CROSS_PREFIX=i686-linux-android
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_VER}
    ;;

    x86_64)
    # android-21或以上平台才支持64位
        TARGET_API=21
        CROSS_PREFIX=x86_64-linux-android
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_64_VER}
    ;;

    *)
        echo "fdk-aac: 不支持编译'$TARGET'目标"
        exit 1
    ;;

esac

# make standalone toolchain
${ANDROID_NDK}/build/tools/make-standalone-toolchain.sh  \
 --platform=android-${TARGET_API}  \
 --toolchain=${TOOLCHAIN_NAME}  \
 --install-dir=${TOOLCHAIN_PATH}

export CC=${TOOLCHAIN_PATH}/bin/${CROSS_PREFIX}-gcc
export CXX=${TOOLCHAIN_PATH}/bin/${CROSS_PREFIX}-g++

# 配置参数
CFG_FLAGS=
CFG_FLAGS="$CFG_FLAGS --prefix=$OUTPUT"
CFG_FLAGS="$CFG_FLAGS --enable-static"
CFG_FLAGS="$CFG_FLAGS --disable-shared"
CFG_FLAGS="$CFG_FLAGS --host=$CROSS_PREFIX"

echo "configurate fdk-aac"
# 生成fdk-aac配置文件
sh autogen.sh
echo "./configure $CFG_FLAGS"
./configure ${CFG_FLAGS}

# 修改libSBRdec/src/lpp_tran.cpp，否则编译失败
# 参考：https://github.com/mstorsjo/fdk-aac/issues/111
sed 's/#ifdef __ANDROID__/#if 0/g' libSBRdec/src/lpp_tran.cpp > libSBRdec/src/lpp_tran.cpp.tmp
rm libSBRdec/src/lpp_tran.cpp
mv libSBRdec/src/lpp_tran.cpp.tmp libSBRdec/src/lpp_tran.cpp

echo "compile fdk-aac"
make -j
make install
